<template>
  <section 
    id="stats" 
    :class="sectionClasses"
    :style="{ 
      '--primary-color': primaryColor,
      '--secondary-color': secondaryColor
    }"
  >
    <div class="container mx-auto px-4 sm:px-6 lg:px-8">
      <div :class="gridClass">
        <div 
          v-for="(stat, index) in stats" 
          :key="index" 
          class="p-6 text-center"
          :style="statItemStyle"
        >
          <div 
            class="text-4xl md:text-5xl font-bold text-primary mb-2 counter"
            :data-target="stat.value"
            :class="{ 'animate-count': animateOnScroll }"
          >
            {{ animateOnScroll ? 0 : stat.valueFormatted || stat.value }}
          </div>
          <p class="text-dark/60">{{ stat.label }}</p>
        </div>
      </div>
    </div>
  </section>
</template>

<script>
export default {
  name: 'StatsCounter',
  // 低代码平台元数据 - 移除语言相关配置
  lowcode: {
    meta: {
      name: 'stats-counter',
      displayName: '数据统计',
      description: '展示公司关键数据统计的组件，支持数字动画效果',
      icon: 'fa-bar-chart',
      category: '数据展示',
      version: '1.0.0',
      isContainer: false
    },
    
    configPanel: [
      {
        title: '基本配置',
        fields: [
          {
            name: 'primaryColor',
            label: '主题色',
            type: 'color',
            defaultValue: '#165DFF'
          },
          {
            name: 'secondaryColor',
            label: '辅助色',
            type: 'color',
            defaultValue: '#36CFC9'
          },
          {
            name: 'bgColor',
            label: '背景色',
            type: 'color',
            defaultValue: '#ffffff'
          }
          // 移除语言选择配置
        ]
      },
      {
        title: '布局配置',
        fields: [
          {
            name: 'columnLayout',
            label: '列布局',
            type: 'select',
            options: [
              { label: '2列', value: '2' },
              { label: '4列', value: '4' },
              { label: '自动适应', value: 'auto' }
            ],
            defaultValue: 'auto'
          },
          {
            name: 'padding',
            label: '内边距',
            type: 'select',
            options: [
              { label: '小', value: 'small' },
              { label: '中', value: 'medium' },
              { label: '大', value: 'large' }
            ],
            defaultValue: 'medium'
          }
        ]
      },
      {
        title: '动画配置',
        fields: [
          {
            name: 'animateOnScroll',
            label: '滚动时动画',
            type: 'boolean',
            defaultValue: true
          },
          {
            name: 'animationDuration',
            label: '动画时长(秒)',
            type: 'number',
            min: 0.5,
            max: 5,
            step: 0.5,
            defaultValue: 2
          }
        ]
      }
    ],
    
    events: [
      {
        name: 'animationComplete',
        label: '动画完成',
        description: '数字动画完成时触发',
        parameters: [
          { name: 'stat', type: 'object', description: '完成动画的统计项' }
        ]
      }
    ],
    
    actions: [
      {
        name: 'updateStats',
        label: '更新统计数据',
        description: '更新统计数字数据',
        parameters: [
          { name: 'stats', type: 'array', required: true, description: '统计数据数组' }
        ]
      },
      {
        name: 'resetAnimation',
        label: '重置动画',
        description: '使数字动画重新开始'
      }
    ]
  },
  
  props: {
    // 颜色配置
    primaryColor: {
      type: String,
      default: '#165DFF'
    },
    secondaryColor: {
      type: String,
      default: '#36CFC9'
    },
    bgColor: {
      type: String,
      default: '#ffffff'
    },
    
    children: {
      type: Array,
      default: () => []
    },
    // 移除语言配置相关props
    
    // 布局配置
    columnLayout: {
      type: String,
      default: 'auto',
      validator: (value) => ['2', '4', 'auto'].includes(value)
    },
    padding: {
      type: String,
      default: 'medium',
      validator: (value) => ['small', 'medium', 'large'].includes(value)
    },
    
    // 动画配置
    animateOnScroll: {
      type: Boolean,
      default: true
    },
    animationDuration: {
      type: Number,
      default: 2,
      validator: (value) => value >= 0.5 && value <= 5
    },
    
    // 统计数据 - 直接使用label而不是labelKey
    stats: {
      type: Array,
      default: () => [
        {
          value: 20,
          valueFormatted: '20+',
          label: '行业经验'
        },
        {
          value: 800,
          valueFormatted: '800+',
          label: '成功案例'
        },
        {
          value: 300,
          valueFormatted: '300+',
          label: '专业团队'
        },
        {
          value: 50,
          valueFormatted: '50+',
          label: '覆盖行业'
        }
      ]
    }
    
    // 移除多语言翻译相关props
  },
  
  data() {
    return {
      // 跟踪哪些统计项已经完成动画
      animatedStats: [],
      // 检测元素是否在视口中
      isInViewport: false
    };
  },
  
  computed: {
    // 网格布局类名
    gridClass() {
      switch (this.columnLayout) {
        case '2':
          return 'grid grid-cols-2 gap-8';
        case '4':
          return 'grid grid-cols-1 md:grid-cols-4 gap-8';
        default: // auto
          return 'grid grid-cols-2 md:grid-cols-4 gap-8';
      }
    },
    
    // 章节样式类
    sectionClasses() {
      let paddingClass = 'py-12';
      
      switch (this.padding) {
        case 'small':
          paddingClass = 'py-8';
          break;
        case 'medium':
          paddingClass = 'py-16';
          break;
        case 'large':
          paddingClass = 'py-24';
          break;
      }
      
      return `${paddingClass} bg-white transition-colors duration-300`;
    },
    
    // 统计项样式
    statItemStyle() {
      return {
        backgroundColor: this.bgColor === '#ffffff' ? 'transparent' : this.bgColor,
        borderRadius: '8px'
      };
    }
  },
  
  watch: {
    // 当统计数据变化时重置动画
    stats() {
      this.animatedStats = [];
      this.resetAnimation();
    },
    
    // 当进入视口时触发动画
    isInViewport(newVal) {
      if (newVal && this.animateOnScroll) {
        this.startAnimations();
      }
    }
  },
  
  mounted() {
    // 初始化滚动监听
    if (this.animateOnScroll) {
      this.checkVisibility();
      window.addEventListener('scroll', this.checkVisibility);
    } else {
      // 如果不需要滚动动画，直接显示最终值
      this.animatedStats = this.stats.map((_, index) => index);
    }
  },
  
  beforeUnmount() {
    window.removeEventListener('scroll', this.checkVisibility);
  },
  
  methods: {
    /**
     * 检查元素是否在视口中
     */
    checkVisibility() {
      const element = this.$el;
      if (!element) return;
      
      const rect = element.getBoundingClientRect();
      const isVisible = (
        rect.top <= (window.innerHeight || document.documentElement.clientHeight) &&
        rect.bottom >= 0
      );
      
      this.isInViewport = isVisible;
    },
    
    /**
     * 开始数字动画
     */
    startAnimations() {
      this.stats.forEach((stat, index) => {
        if (!this.animatedStats.includes(index)) {
          this.animateCounter(index, stat.value);
        }
      });
    },
    
    /**
     * 数字动画实现
     */
    animateCounter(index, target) {
      const element = this.$el.querySelectorAll('.counter')[index];
      if (!element) return;
      
      let start = 0;
      const duration = this.animationDuration * 1000; // 转换为毫秒
      const increment = target / (duration / 16); // 假设60fps
      const startTime = performance.now();
      
      const updateCounter = (timestamp) => {
        const elapsedTime = timestamp - startTime;
        
        if (start < target && elapsedTime < duration) {
          start += increment;
          // 确保不会超过目标值
          if (start > target) start = target;
          
          // 更新显示值，使用格式化值或原始值
          element.textContent = this.stats[index].valueFormatted || Math.floor(start);
          requestAnimationFrame(updateCounter);
        } else {
          // 动画完成，使用最终值
          element.textContent = this.stats[index].valueFormatted || target;
          this.animatedStats.push(index);
          this.$emit('animationComplete', this.stats[index]);
        }
      };
      
      requestAnimationFrame(updateCounter);
    },
    
    /**
     * 更新统计数据
     */
    updateStats(newStats) {
      if (Array.isArray(newStats)) {
        this.stats = newStats;
      }
    },
    
    /**
     * 重置动画
     */
    resetAnimation() {
      this.animatedStats = [];
      const counters = this.$el.querySelectorAll('.counter');
      counters.forEach((counter, index) => {
        counter.textContent = '0';
      });
      
      // 如果元素在视口中，立即重新开始动画
      if (this.isInViewport && this.animateOnScroll) {
        setTimeout(() => this.startAnimations(), 100);
      }
    }
  }
};
</script>

<style scoped>
/* 主题色适配 */
.text-primary {
  color: var(--primary-color) !important;
}

/* 统计数字样式 */
.counter {
  transition: all 0.3s ease;
  font-variant-numeric: tabular-nums; /* 确保数字对齐 */
}

/* 动画相关样式 */
.animate-count {
  animation: counter-pulse 0.5s ease-in-out;
}

@keyframes counter-pulse {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
}

/* 文本样式 */
.text-dark\/60 {
  color: rgba(31, 41, 55, 0.6);
  font-size: 1rem;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .counter {
    font-size: 2.5rem !important;
  }
}
</style>
